<script setup lang="ts">
import { ref } from 'vue';
import { useUploadStore } from '../../stores/uploadStore';
import imageUploadService from '../../services/ImageUploadService';
// No imports needed

const uploadStore = useUploadStore();
const fileInput = ref<HTMLInputElement | null>(null);
const isDragging = ref(false);
const errorMessage = ref<string | null>(null);
const showError = ref(false);

async function processFiles(files: FileList) {
  if (files.length === 0) return;
  
  // Clear previous error
  errorMessage.value = null;
  showError.value = false;
  
  const imageFiles: File[] = [];
  
  // Filter only image files
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    if (imageUploadService.validateImage(file)) {
      imageFiles.push(file);
    }
  }
  
  if (imageFiles.length === 0) {
    errorMessage.value = '请选择有效的图片文件 (JPEG, PNG, WebP)';
    showError.value = true;
    return;
  }
  
  // Check if adding these images would exceed the limit
  const countValidation = imageUploadService.validateImageCount(
    uploadStore.images.length, 
    imageFiles.length
  );
  
  if (!countValidation.valid) {
    errorMessage.value = countValidation.message || '图片数量超出限制';
    showError.value = true;
    return;
  }
  
  uploadStore.setUploading(true);
  
  try {
    // Use the progress tracking feature
    const uploadedImages = await imageUploadService.uploadImages(
      imageFiles,
      (progress) => {
        uploadStore.setUploadProgress(progress);
      }
    );
    
    if (uploadedImages.length === 0) {
      errorMessage.value = '没有有效的图片可以上传';
      showError.value = true;
      return;
    }
    
    if (uploadedImages.length < imageFiles.length) {
      errorMessage.value = `部分图片 (${imageFiles.length - uploadedImages.length}/${imageFiles.length}) 无法上传，可能尺寸过大或格式不支持`;
      showError.value = true;
    }
    
    uploadStore.addImages(uploadedImages);
  } catch (error: any) {
    console.error('上传图片失败:', error);
    errorMessage.value = error.message || '上传图片失败，请重试';
    showError.value = true;
  } finally {
    uploadStore.setUploading(false);
  }
}

function handleFileSelect(event: Event) {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    processFiles(input.files);
    // Reset the input so the same file can be selected again
    input.value = '';
  }
}

function openFileDialog() {
  if (fileInput.value) {
    fileInput.value.click();
  }
}

function handleDragOver(event: DragEvent) {
  event.preventDefault();
  isDragging.value = true;
}

function handleDragLeave() {
  isDragging.value = false;
}

function handleDrop(event: DragEvent) {
  event.preventDefault();
  isDragging.value = false;
  
  if (event.dataTransfer?.files && event.dataTransfer.files.length > 0) {
    processFiles(event.dataTransfer.files);
  }
}
</script>

<template>
  <div 
    class="image-uploader"
    :class="{ dragging: isDragging }"
    @dragover="handleDragOver"
    @dragleave="handleDragLeave"
    @drop="handleDrop"
  >
    <div class="upload-area">
      <div class="upload-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24">
          <path fill="currentColor" d="M19.35 10.04A7.49 7.49 0 0 0 12 4C9.11 4 6.6 5.64 5.35 8.04A5.994 5.994 0 0 0 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5c0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5l5 5h-3z"/>
        </svg>
      </div>
      <p>拖放图片到此处或</p>
      <button 
        @click="openFileDialog"
        aria-label="选择图片上传"
        tabindex="0"
        @keydown.enter="openFileDialog"
        @keydown.space="openFileDialog"
      >
        选择图片
      </button>
      <input 
        ref="fileInput"
        type="file" 
        accept="image/jpeg,image/png,image/webp"
        multiple
        @change="handleFileSelect"
        style="display: none"
        aria-hidden="true"
      >
    </div>
    <div v-if="uploadStore.isUploading" class="upload-progress">
      <div class="progress-bar">
        <div 
          class="progress-fill"
          :style="{ width: uploadStore.uploadProgress + '%' }"
        ></div>
      </div>
      <p>上传中... {{ uploadStore.uploadProgress }}%</p>
    </div>
    <div v-if="showError" class="error-message">
      <p>{{ errorMessage }}</p>
    </div>
  </div>
</template>

<style scoped>
.image-uploader {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  transition: all 0.3s ease;
}

.image-uploader.dragging {
  border-color: #4caf50;
  background-color: rgba(76, 175, 80, 0.1);
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.upload-icon {
  color: #666;
}

button {
  padding: 0.5rem 1rem;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

button:hover {
  background-color: #45a049;
}

.upload-progress {
  margin-top: 1rem;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

.progress-fill {
  height: 100%;
  background-color: #4caf50;
  transition: width 0.3s ease;
}

.error-message {
  margin-top: 1rem;
  padding: 0.75rem;
  background-color: #ffebee;
  border: 1px solid #ffcdd2;
  border-radius: 4px;
  color: #c62828;
}
</style>